/**
 * 七巧板跳转，有待完善
 */

const vscode = require('vscode');
const path = require('path');
const fs = require('fs');
const util = require('../util');

/**
 * 查找文件定义的provider
 * @param {*} document 
 * @param {*} position 
 * @param {*} token 
 */
function provideDefinition(document, position, token) {
    const fileName    = document.fileName;
    const workDir     = path.dirname(fileName);
    const line        = document.lineAt(position);
    const projectPath = util.getProjectPath(document);
    
    if (workDir.indexOf(`${projectPath}/app/view/layout`) >= 0) {
        const result = /\{%\s*using\s*"([\w\/\.]+)"\s*%\}/g.exec(line.text);
        if (!result) return;
        const key = result[1];

        const destPath = `${projectPath}/app/view/${result[1]}`;
        if (fs.existsSync(destPath)) {
            util.addGoldLog('definition-view');
            return new vscode.Location(vscode.Uri.file(destPath), new vscode.Position(0, 0));
        } else {
            console.warn('不存在文件：' + destPath);
        }
    }
}
module.exports = function(context) {
    // 注册如何实现跳转到定义
    context.subscriptions.push(vscode.languages.registerDefinitionProvider(['html'], {
        provideDefinition
    }));
};